<template>
  <!-- 结算页面 -->
  <div class="settle-account">
    <van-nav-bar
      title="确认下单"
      fixed
      :placeholder="true"
      left-arrow
      @click-left="backRouter"
    >
      <template #left>
        <van-icon name="arrow-left" color="#a8a9aa" size="18" />
      </template>
    </van-nav-bar>
    <div class="settle">
      <div class="way">堂食</div>

      <div class="table-numbertable-number">桌号: D4桌</div>

      <div class="billInfo-box">
        <div class="base-info">
          <div class="shop-name">明月阁西餐厅</div>
          <div class="cur-date">用餐日期: {{ new Date() | toMonthAndDay }}</div>
        </div>
        <div
          class="list-info"
          v-for="typeList in bill"
          :key="typeList.mealTypeName"
        >
          <div class="list-title">{{ typeList.mealTypeName }}:</div>
          <div
            class="list-item"
            v-for="item in typeList.goodsList"
            :key="item.mealId"
          >
            <div class="item-img">
              <img :src="item.mealPictures[0]" :alt="item.mealName" />
            </div>
            <div class="item-details">
              <div class="name">{{ item.mealName }}</div>
              <div class="unit">份</div>
              <div class="count">X{{ item.buyCount }}</div>
            </div>
            <div class="price">
              ￥{{ (item.mealPrice * item.buyCount) | toFixed_2 }}
            </div>
          </div>
        </div>
      </div>

      <div class="calculate">
        <div class="total">
          <div class="total-title">商品总价</div>
          <div class="total-number">￥{{ originTotal }}</div>
        </div>
        <div class="final-total">
          <div class="final-total-title">小计</div>
          <div class="final-total-price">￥{{ finalTotal }}</div>
        </div>
      </div>

      <div class="extra-info">
        <div class="pay">
          <div class="title">支付</div>
          <div class="mode">在线支付</div>
        </div>
        <div class="remark">
          <!-- <div class="title">备注</div> -->
          <!-- <div class="content">30字以内</div> -->
          <van-field
            v-model="orderDemand"
            rows="2"
            label="备注"
            autosize
            type="textarea"
            maxlength="30"
            placeholder="30字以内"
            class="content"
            show-word-limit
          />
        </div>
      </div>
    </div>

    <div class="commit-box">
      <div class="commit-total-price">
        合计:<span class="commit-total-price-number"> ￥{{ finalTotal }} </span>
      </div>
      <div class="commit-btn" @click="commitBill">提交订单</div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import { createOrder } from '@/api/orderApi';
export default {
  name: "settleAccount",
  data() {
    return {
      bill: [],
      orderDemand: ''
    };
  },
  created() {
    // 进入页面的初始化
    this.init();
  },
  methods: {
    ...mapMutations("m_user", ["setBillList", "setPayOrder", "setQRInfo"]),
    backRouter() {
      this.$router.go(-1);
    },
    init() {
      if (!this.$route.query.billInfo || this.billList.length <= 0) {
        // 说明不是结算按钮过来的, 直接不处理
        // 当vuex中的billList没有值时说明了不会从结算按钮过来的
        return;
      }

      let tempBillList = this.$route.query.billInfo;

      // 防止直接刷新的时候, 数据变成全部是[object Object]这样, 导致下面的调用属性出错
      if (this.$route.query.billInfo[0] === "[object Object]") {
        tempBillList = this.billList;
      }
      // 分类处理billInfo, 同一种类在一个数组中
      let map = new Map();
      for (let i = 0, index = 0, len = tempBillList.length; i < len; i++) {
        if (map.has(tempBillList[i].mealTypeId)) {
          // 存在
          let curIndex = map.get(tempBillList[i].mealTypeId);
          this.bill[curIndex].goodsList.push(tempBillList[i]);
        } else {
          // 不存在
          map.set(tempBillList[i].mealTypeId, index);
          this.bill[index] = {
            mealTypeName: tempBillList[i].mealType,
            goodsList: [],
          };
          this.bill[index].goodsList.push(tempBillList[i]);
          // 下次又有新的类的时候, 往数组后添加
          index++;
        }
      }
      // console.log(this.bill);
    },
    async commitBill() {
      if (this.bill.length <= 0) {
        this.$toast.fail("当前未存在订单");
        return;
      }

      let body = this.formatSendData(); // 格式化订单数据, 返回请求体的数据
      let res = await createOrder(body);
      // 清除LocalStorage和vuex中购物车信息,
      localStorage.removeItem("shopCar");
      this.setBillList([]);

      // 标志存在未支付订单, false表示存在订单并且未支付
      this.setPayOrder(false);
      this.setQRInfo(Object.assign({
        time: 1000 * 60 * 2
      }, res.data));

      // 跳转到二维码扫描支付页面
      this.$router.push({
        path: "/pay",
        query: {
          payInfo: res.data,
        },
      });
    },
    formatSendData() {
      let mealItems = [];

      this.bill.forEach((typeList) => {
        typeList.goodsList.forEach((goods) => {
          let tempResult = {
            mealId: goods.mealId,
            purchaseNum: goods.buyCount,
          };
          mealItems.push(tempResult);
        });
      });
      let body = {
        // userId: this.userInfo.userId,
        seatId: 0, // 未知
        orderDemand: "", // 未知
        mealItems,
      };

      return body;
    },
  },
  filters: {
    toFixed_2(val) {
      return Number(Number(val).toFixed(2));
    },
    toMonthAndDay(val) {
      return `${val.getMonth() + 1}-${val.getDate()}`;
    },
  },
  computed: {
    ...mapState("m_user", ["billList", "userInfo"]),
    originTotal() {
      let result = this.bill.reduce((init, item) => {
        let listTotal = item.goodsList.reduce((awt, goods) => {
          return awt + goods.mealPrice * goods.buyCount;
        }, 0);
        return init + listTotal;
      }, 0);
      return Number(Number(result).toFixed(2));
    },
    finalTotal() {
      let discounts = 0;
      let result = this.bill.reduce((init, item) => {
        let listTotal = item.goodsList.reduce((awt, goods) => {
          return awt + goods.mealPrice * goods.buyCount;
        }, 0);
        return init + listTotal;
      }, 0);
      return Number(Number(result).toFixed(2)) - discounts;
    },
  },
};
</script>

<style lang="scss" scoped>
$price_color: rgb(212, 3, 3);

.settle {
  background-color: #f0f0f0;
  padding: 10px 10px 55px 10px;
}

.way {
  //   display: flex;
  //   justify-content: center;
  //   align-items: center;
  width: 80px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  background-color: #43a8f1;
  border-radius: 20px;
  color: #fff;
  font-size: 15px;
}

.table-numbertable-number {
  padding: 15px 10px;
  margin: 10px 0;
  background-color: #fff;
  font-size: 15px;
}

.billInfo-box {
  background-color: #fff;
  padding: 10px;

  .base-info {
    font-size: 15px;
    padding-bottom: 10px;
    border-bottom: 1px solid #ccc;

    .shop-name {
      color: #ababab;
      margin: 10px 0;
    }
    .cur-date {
      font-size: 14px;
    }
  }

  .list-info {
    .list-title {
      padding: 10px 0;
    }
    .list-item {
      display: flex;
      justify-content: space-between;
      margin: 10px 0;

      .item-img {
        width: 80px;
        height: 60px;
        border-radius: 5px;
        overflow: hidden;
      }
      .item-details {
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        flex-grow: 1;
        margin: 0 10px;

        .name {
          font-size: 14px;
        }
        .unit {
          font-size: 12px;
          color: rgb(168, 168, 168);
        }
        .count {
          font-size: 14px;
          color: $price_color;
        }
      }
      .price {
        font-size: 14px;
        color: $price_color;
      }
    }
  }
}

.calculate {
  padding: 20px 10px;
  background: #fff;
  font-size: 14px;
  margin: 10px 0;

  .total {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .total-number {
      font-size: 12px;
      color: $price_color;
    }
  }

  .final-total {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-top: 20px;

    .final-total-price {
      margin-left: 10px;
      font-weight: 700;
      font-size: 12px;
      color: $price_color;
    }
  }
}

.extra-info {
  padding: 0 10px;
  margin: 10px 0;
  background-color: #fff;

  .pay {
    display: flex;
    justify-content: space-between;
    padding: 10px;
    font-size: 14px;
  }

  .remark {
    padding: 0 10px;
    border-top: 1px solid rgb(236, 235, 235);
    .title {
      width: 40px;
    }
    .content {
      padding: 10px 0;
      color: #ababab;
    }
  }
}

.commit-box {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 0;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 55px;
  padding-left: 20px;
  background-color: #fff;

  .commit-total-price {
    // display: flex;
    // align-items: center;
    // height: 100%;
    font-size: 16px;
    color: $price_color;

    .commit-total-price-number {
      margin-left: 3px;
      font-size: 15px;
    }
  }

  .commit-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    padding: 0 30px;
    background-color: #41aaee;
    color: #fff;
    font-size: 14px;
  }
}

::v-deep .van-nav-bar__content {
  height: 60px !important;
}
</style>
